/**
 * FileName: UserServiceImpl
 * Author:   Administrator
 * Date:     2018/11/16 17:06
 * Description: 后台用户逻辑实现
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.fortune.rainshinesystem.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.SysUsers;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.model.system.UserRole;
import com.fortune.rainshinecommon.query.UserIdQuery;
import com.fortune.rainshinecommon.query.UserQuery;
import com.fortune.rainshinecommon.util.EndecryptUtil;
import com.fortune.rainshinesystem.mapper.SysUsersMapper;
import com.fortune.rainshinesystem.mapper.UserMapper;
import com.fortune.rainshinesystem.mapper.UserRoleMapper;
import com.fortune.rainshinesystem.service.UserService;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 〈一句话功能简述〉<br>
 * 〈后台用户逻辑实现〉
 *
 * @author Administrator
 * @create 2018/11/16
 * @since 1.0.0
 */
@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private SysUsersMapper mapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public MsgModel addUser(User user) {
        try {
            if(user.getUsername() == null){
                return new MsgModel("帐号不能为空", ResultCode.FAILURE);
            }
            if(user.getRoles() == null || user.getRoles().isEmpty()){
                return new MsgModel("角色不能为空", ResultCode.FAILURE);
            }
            Wrapper<User> wrapper = new EntityWrapper<>();
            wrapper.eq("username", user.getUsername());
            List<User> users = Optional.ofNullable(userMapper.selectList(wrapper)).orElse(Lists.newArrayList());
            if(!users.isEmpty()){
                return new MsgModel("此帐号已存在", ResultCode.FAILURE);
            }
            user.setPassword(EndecryptUtil.encrytMd5(user.getPassword(), user.getUsername(), 3));
            user.setState(0);
            user.setCreateTime(new Date());
            userMapper.insert(user);
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(user.getRoles().get(0).getRoleId());
            userRole.setCreateId(user.getCreateId());
            userRole.setCreateTime(new Date());
            userRole.setUpdateId(user.getUpdateId());
            userRole.setUpdateTime(new Date());
            userRoleMapper.insert(userRole);
            return new MsgModel(ResultCode.SUCCESS, user.getUsername());
        } catch (Exception e) {
            logger.error("UserServiceImpl addUser ====> {}", e);
            return new MsgModel("添加用户异常", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel list() {
        try {
            List<SysUsers> users = mapper.selectList();
            return new MsgModel(ResultCode.SUCCESS, users);
        } catch (Exception e) {
            logger.error("UserServiceImpl list ====> {}", e);
            return new MsgModel("获取列表异常", ResultCode.FAILURE);
        }
    }

    @Override
    public List<User> getShopAssistantsByShopId(Integer shopId, Integer state) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        if(state != null){
            wrapper.eq("state", state);
        }
        return Optional.ofNullable(userMapper.selectList(wrapper)).orElse(Lists.newArrayList());
    }

    @Override
    public List<User> getUsersByPhone(String phone) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("phone", phone);
        return Optional.ofNullable(userMapper.selectList(wrapper)).orElse(Lists.newArrayList());
    }

    @Override
    public MsgModel updatePsw(UserQuery query) {
        if(query.getUserId() == null){
            return new MsgModel("登录账号异常", ResultCode.FAILURE);
        }
        if(StringUtils.isBlank(query.getOldPsw())){
            return new MsgModel("请输入原密码", ResultCode.FAILURE);
        }
        if(StringUtils.isBlank(query.getNewPsw())){
            return new MsgModel("请输入新密码", ResultCode.FAILURE);
        }
        if(StringUtils.equals(query.getOldPsw(),query.getNewPsw())){
            return new MsgModel("新密码不能和原密码相同", ResultCode.FAILURE);
        }
        try{
            User user = userMapper.selectById(query.getUserId());
            if(user == null){
                return new MsgModel("无此用户", ResultCode.FAILURE);
            }
            String finalSecret = EndecryptUtil.encrytMd5(query.getOldPsw(), user.getUsername(), 3);
            if (!finalSecret.equals(user.getPassword())) {
                return new MsgModel("原密码输入不正确", ResultCode.FAILURE);
            }
            user.setPassword(EndecryptUtil.encrytMd5(query.getNewPsw(), user.getUsername(), 3));
            if (userMapper.updateById(user) > 0) {
                return new MsgModel("修改密码成功", ResultCode.SUCCESS);
            } else {
                return new MsgModel("修改密码失败", ResultCode.FAILURE);
            }
        }catch (Exception e){
            logger.error("updatePsw ====> {}", e);
            return new MsgModel("修改密码异常", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel updateAvatar(UserQuery query) {
        if(query.getUserId() == null){
            return new MsgModel("登录账号异常", ResultCode.FAILURE);
        }
        if(StringUtils.isBlank(query.getAvatar())){
            return new MsgModel("请上传头像图片", ResultCode.FAILURE);
        }
        try{
            User user = userMapper.selectById(query.getUserId());
            if(user == null){
                return new MsgModel("无此用户", ResultCode.FAILURE);
            }
            user.setAvatar(query.getAvatar());
            if (userMapper.updateById(user) > 0) {
                return new MsgModel("修改头像成功", ResultCode.SUCCESS);
            } else {
                return new MsgModel("修改头像失败", ResultCode.FAILURE);
            }
        }catch (Exception e){
            logger.error("updateAvatar ====> {}", e);
            return new MsgModel("修改头像异常", ResultCode.FAILURE);
        }
    }

    @Override
    public MsgModel getAllMerchants(UserIdQuery query) {
        logger.info("getAllMerchants query ====> {}", query);
        if(query.getUserId() == null){
            return new MsgModel("登录账号异常", ResultCode.FAILURE);
        }
        int roleId = userRoleMapper.getRoleIdByUserId(query.getUserId());
        if(roleId != 2){
            return new MsgModel("无此权限", ResultCode.FAILURE);
        }
        try{
            Page<User> page = new Page<>(query.getPage(), query.getLimit());
            List<User> merchantList = Optional.ofNullable(userMapper.getAllMerchants(page)).orElse(Lists.newArrayList());
            page.setRecords(merchantList);
            return new MsgModel(page.getRecords().size(),page.getRecords());
        }catch (Exception e){
            logger.error("getAllMerchants ====> {}", e);
            return new MsgModel("获取招商列表异常", ResultCode.FAILURE);
        }
    }

}